package common.service.base.common;


import java.security.SecureRandom;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import common.service.util.AesUtil;
import common.service.util.RedisUtil;
import common.service.util.TimeUtil;

/**
 * @ClassName SessionIdGenerator
 * @Description 生成会话id
 * @Author lixin
 * @Date 2020/02/10 下午3:41
 * Version 0.0.1
 **/
@Service
public class SessionIdGenerator {
	private final static  int sessionIdLength = 16;
	private static 	SecureRandom rd =  new SecureRandom();
	
	@Autowired
	private RedisUtil redisUtil;
	
	public   String generateSessionId(){
		String result = null;
		byte[] random = new byte[16];
		StringBuilder buffer = new StringBuilder();
		int resultLenBytes = 0;
		do{
			if(result != null){
				buffer = new StringBuilder(); 
			}
			while(resultLenBytes < sessionIdLength){
				getRandomBytes(random);
				for(int j = 0; j < random.length && resultLenBytes < sessionIdLength; j++){
					byte b1 = (byte)((random[j] & 0xf0) >> 4);
					byte b2 = (byte)(random[j] & 0x0f);
					if(b1 < 10){
						buffer.append((char)('0' + b1));
					}else{
						buffer.append((char)('A'+(b1 - 10)));
					}
					if(b2 < 10){
						buffer.append((char)('0' + b2));
					}else{
						buffer.append((char)('A' + (b2 - 10)));
					}
					resultLenBytes++;
				}
			}
			result = buffer.toString()+ AesUtil.encrypt(TimeUtil.getCurrentTime17ByMillis());
			if(result.length()>96){
				result =result.substring(0,96);
	        }
		}while(redisUtil.hasKey(result));

		return result;
	}
	private  void  getRandomBytes(byte[] random) {
		rd.nextBytes(random);
	}


}
